<template>
    <page-meta :page-style="'overflow:' + (goodsData.show || isopenDecorate ? 'hidden' : 'visible')"> </page-meta>

    <NetworkError v-if="state.networkErrorShow" v-on:tautology="requestHandle" />
    <SkeletonHome v-if="skeletonLoading" />
    <view class="home_main" v-else>
        <u-navbar :placeholder="true" @leftClick="toShop">
            <template #left>
                <view class="navbar">
                    <view class="navbar_name"> {{ state.shopName }} </view>
                    <u-icon v-if="state.choose" size="16" color="#333333" name="arrow-right"></u-icon>
                </view>
            </template>
        </u-navbar>
        <view v-if="state.shopDisabled" class="shop_disabled">
            <image class="shop_disabled_img" :src="getImgOssUrl('/ui-prod-2.0.0/close.png')" />
            <view class="shop_disabled_text">
                <text>该店铺已歇业，欢迎下次光临</text>
            </view>
        </view>
        <template v-else>
            <view :style="{ opacity: loadData ? 1 : 0 }" class="tabbar_padding_b">
                <Decorate
                    :datas="options"
                    @openPop="isopenDecorate = true"
                    @closePop="isopenDecorate = false"
                    @updataCoupon="getDecorate()"
                    :hasTabbar="true" />
            </view>

            <uni-popup ref="popup" :safe-area="false" @change="change">
                <view class="popup-content popup_padding_b">
                    <view class="pop_cancel" @click.stop="cancel">
                        <img class="pop_logo" :src="getImgOssUrl('/ui-prod-2.0.0/cancel_1.1.png')"
                    /></view>
                    <skupop
                        :goodsId="goodsData.goodsId"
                        :goodsNo="goodsData.goodsNo"
                        :show="goodsData.show"
                        @popup="popup.open('bottom')"
                        @close="close"
                        @buyGoods="toConfirm"
                /></view>
            </uni-popup>
            <view class="float-box-home">
                <customerServiceFloat :showIcons="showIcons" :shareAppMessage="shareAppMessage" />
            </view>
            <el-loading></el-loading>
        </template>
    </view>
    <!-- 隐私监听 -->
    <el-privacy-listener-popup :is-handle-tab-bar="false"></el-privacy-listener-popup>
    <TabBar v-show="!state.shopDisabled" url="/pages/tabbar/home" />
</template>
<script setup>
import SkeletonHome from '@/components/skeletonHome';
import NetworkError from '@/components/networkError';
import TabBar from '@/components/tabBar';
import { ref, reactive, computed } from 'vue';
import { onShow, onPullDownRefresh, onHide, onPageScroll, onShareAppMessage } from '@dcloudio/uni-app';
import request from '@/request';
import router from '@/router';
import storage from '@/commons/storage';
import Decorate from '@/components/decorate';
import skupop from '@/components/skupop';
import customerServiceFloat from '@/components/customerServiceFloat';
import { getImgOssUrl, isObject, isEmpty, floatDivide, isNotEmpty } from '@/commons/utils.js';
import { useTrace } from '@/commons/trace';
import { getCorpInfo, getTabBarInfo, getParamsBySceneHook, touristLoginHandler } from '@/hooks';

const skeletonLoading = ref(true);
const scrollTop = ref(0);
const goodsData = reactive({ goodsId: '', goodsNo: '', show: false });
const { traceStart, traceStay, traceLoad, traceReport } = useTrace();
const state = reactive({
    shopList: [],
    /* 当前店铺是否可以切换 */
    choose: false,
    // 当前店铺是否禁用
    shopDisabled: false,
    shopId: '',
    shopName: '',
    networkErrorShow: false
});
let isopenDecorate = ref(false);
let loadData = ref(0);
//记录操作加购商品是左边商品还是右边
let type = ref();
//记录操作加购商品的索引
const hotIndex = ref();
const popup = ref();
const isDecorate = ref(false);
const showServiceFloat = ref(false);
const options = reactive({ data: {}, shareImg: '', shareTitle: '' });
const props = defineProps({
    shopId: {
        type: [String, Number],
        default: ''
    },
    scene: {
        type: String,
        default: ''
    }
});
const lefthotGoods = ref([]);
const righthotGoods = ref([]);
// 下拉刷新
onPullDownRefresh(() => {
    getDecorate();
    getTabBarInfo();
    setTimeout(function () {
        uni.stopPullDownRefresh();
    }, 500);
});

/* 跳转至店铺列表 */
const toShop = () => {
    if (state.choose) {
        router.push({ path: '/pages-home/shop/index' });
    }
};

/**
 * 获取经纬度信息
 */
const getLocation = corp => {
    return new Promise(resolve => {
        let shopId = storage.get('ZW_SHOP_ID');
        let shopName = '';
        uni.getLocation({
            type: 'gcj02',
            altitude: true,
            success: async res => {
                const latitude = res.latitude;
                const longitude = res.longitude;

                if (isEmpty(shopId)) {
                    const result = await request('shopRecentlyInfo', { lan: latitude, lng: longitude });

                    shopId = result.data.id;
                    shopName = result.data.shopName;

                    // 调试的时候可以打开下边两行代码
                    // shopId = corp.shopList[0]?.id;
                    // shopName = corp.shopList[0]?.shopName;
                } else {
                    shopName = corp?.shopList?.filter(v => v.id === shopId)[0]?.shopName;
                }

                resolve({ shopId, shopName });
            },
            fail: () => {
                /**
                 * shopId为空  默认取第一个
                 * shopId缓存不为空：1. 店铺选择的，这个时候name有值  2.  传值shopId进来的， name为空
                 */
                if (isEmpty(shopId)) {
                    shopId = corp.shopList[0]?.id;
                    shopName = corp.shopList[0]?.shopName;
                } else {
                    shopName = corp?.shopList?.filter(v => v.id == shopId)[0]?.shopName;
                }
                resolve({ shopId, shopName });
            }
        });
    });
};

/**
 * 处理门店信息
 */
const setShopInfo = async () => {
    const corp = await getCorpInfo();
    let shopName;
    let shopId;
    // 判断一下开启的店铺数量，单门店商户就不弹出地址授权弹框
    if (corp.shopList.length > 1) {
        const loc = await getLocation(corp);
        shopId = loc.shopId;
        shopName = loc.shopName;
    } else {
        if (isEmpty(storage.get('ZW_SHOP_ID'))) {
            shopId = corp.shopList[0]?.id;
            shopName = corp.shopList[0]?.shopName;
        } else {
            shopId = storage.get('ZW_SHOP_ID');
            shopName = corp?.shopList?.filter(v => v.id == shopId)[0]?.shopName;
        }
    }
    // 当前店铺停用取缓存 缓存没有 显示 店铺已歇业
    state.shopName = shopName || storage.get('shopName') || '店铺已歇业';
    state.shopList = corp.shopList || [];
    // 当前店铺是否禁用, 当前店铺 id 在 shopList 中表示未禁用
    state.shopDisabled = !state.shopList.some(item => item.id == shopId);
    /* 只有一个门店，不支持切换 或 当前店铺已停用，支持切换 */
    state.choose = state.shopList.length > 1 || state.shopDisabled;
    storage.set('ZW_SHOP_ID', Number(shopId));
    storage.set('shopName', state.shopName);
    // 第一次进入小程序时获取游客身份
    touristLoginHandler();
};

/**
 * 获取轮播图数据/热销商品数据
 */
const requestHandle = async () => {
    isopenDecorate.value = false;
    if (state.networkErrorShow) skeletonLoading.value = true;
    try {
        userId.value = storage.get('userId');
        uni.hideTabBar();
        traceStart();
        if (props.scene) {
            // 分享弹窗生成的二维码跳转的
            const res = await getParamsBySceneHook(props.scene, 1);
            res?.shopId && storage.set('ZW_SHOP_ID', Number(res?.shopId));
            // 重定向首页，避免切换店铺返回后有scene参数，无法切换店铺更改缓存
            router.reLaunch({
                url: '/pages/tabbar/home'
            });
        } else if (props.shopId) {
            // 如果参数上带有shopId,比如分享朋友圈，短链，分享给好友的链接
            storage.set('ZW_SHOP_ID', Number(props.shopId));
            // 重定向首页，避免切换店铺返回后有scene参数，无法切换店铺更改缓存
            router.reLaunch({
                url: '/pages/tabbar/home'
            });
        }
        await setShopInfo();
        traceLoad('visit_page_home');
        getTabBarInfo();
        getDecorate();
        getLogo();
        hasCustomerService();
    } catch (error) {
        skeletonLoading.value = false;
        if (isObject(error)) {
            uni.showToast({
                title: error.data.msg,
                icon: 'none',
                duration: 3000
            });
        }
    }
};

onShow(requestHandle);

/**
 * 客服入口
 */
// todo: 以后优化接口放入组件中
const showIcons = computed(() => {
    return showServiceFloat.value ? ['share', 'service'] : ['share'];
});
const hasCustomerService = async () => {
    let res = await request('openServer');
    storage.set('openServerMes', JSON.stringify(res.data));
    showServiceFloat.value = res.data.indexPage === 2;
};
// 转换优惠券内容
const couponContent = obj => {
    const { couponPrerequisites, couponMatch, couponPrerequisitesAdditional, couponDiscountContent } = obj;
    const pre = [
        '无门槛，',
        `满${floatDivide(couponPrerequisitesAdditional, 100)}元，`,
        `满${couponPrerequisitesAdditional}件，`
    ];
    const num = [`全部商品`, `部分商品`, '部分商品'];
    return (pre[couponPrerequisites - 1] || '') + (num[couponMatch - 1] || '');
};

const logoImg = ref();
const getLogo = async () => {
    // 获取小程序logo
    const { data } = await request('shopIdServ');
    logoImg.value = (data || {})?.tenantInfo?.logo;
};
let userId = ref(storage.get('userId'));
const shareAppMessage = computed(() => {
    const shopName = storage.get('shopName');
    const shopId = storage.get('ZW_SHOP_ID');
    // const currentRoutes =  ();
    // console.log(shopName, currentRoutes);
    // todo:活动中的页面，以及邀请人的id,shopId
    let data = {
        title: options?.shareTitle || '超多好物等你来享，快来一起逛逛吧~', // 分享名称或店铺名称
        path: `/pages/tabbar/home?shopId=${shopId}&inviteMemberId=${userId.value}`, // url + 原有参数
        imageUrl: options?.shareImg || logoImg?.value || getImgOssUrl('/ui-prod-2.0.0/errorImg.png') // todo:分享设置的图片如果没有就是logo图
    };
    return data;
});

/**
 * 获取首页装修信息
 */
const getDecorate = () => {
    request('decorateServ', {
        pageCode: 'home',
        isPreview: 2,
        shopId: storage.get('ZW_SHOP_ID')
    })
        .then(async res => {
            state.networkErrorShow = false;
            if (Object.keys(res.data).length && res.data.components) {
                let getData = JSON.parse(JSON.stringify(options.data));
                Object.assign(getData, res.data);
                options.shareImg = getData.shareImg;
                options.shareTitle = getData.shareTitle;
                let productIds = [];
                let seckillIds = [];
                let groupbuyIds = [];
                let couponIds = [];

                let components = JSON.parse(getData.components);
                components.forEach(async (item, index) => {
                    if (item.component.name == 'PlaceHolderView') {
                        components.splice(index, 1);
                        return;
                    }
                    if (item.component.name == 'product') {
                        productIds = [...productIds, ...item.options.imgList];
                    } else if (item.component.name == 'seckill') {
                        seckillIds = [...seckillIds, ...item.options.imgList];
                    } else if (item.component.name == 'groupbuy') {
                        if (item.options.addType == 1) {
                            groupbuyIds = [...groupbuyIds, ...item.options.imgList];
                        }
                    } else if (item.component.name == 'coupon') {
                        couponIds = [...couponIds, ...item.options.imgList];
                    }
                });
                let productData = [];
                let seckillData = [];
                let groupData = [];
                let couponData = [];
                if (couponIds.length) {
                    couponData = await request('couponList', { couponIds: couponIds, userId: storage.get('userId') });
                }
                if (productIds.length) {
                    productData = await request('goodsList', { goodsId: productIds });
                }
                if (seckillIds.length) {
                    seckillData = await request('seckillList', { activityId: seckillIds });
                }
                if (groupbuyIds.length) {
                    groupData = await request('seckillListManual', { activityId: groupbuyIds });
                }
                let param = await Promise.all(
                    components.map(async item => {
                        const name = item.component.name;
                        const imgLists = {
                            product: isNotEmpty(productData?.data) ? productData?.data : [],
                            seckill: isNotEmpty(seckillData?.data) ? seckillData?.data : [],
                            groupbuy: isNotEmpty(groupData?.data) ? groupData?.data : [],
                            coupon: isNotEmpty(couponData?.data) ? couponData?.data : []
                        };
                        if (name == 'product' || name == 'seckill') {
                            item.options.imgList.forEach((id, indexs) => {
                                let proItem = imgLists[name].filter(val => val.id == id);
                                if (proItem.length) {
                                    item.options.imgList[indexs] = proItem[0];
                                } else {
                                    item.options.imgList[indexs] = null;
                                }
                            });
                        }
                        if (name == 'coupon') {
                            item.options.imgList.forEach((id, indexs) => {
                                let proItem = imgLists[name].filter(val => val.id == id);
                                if (proItem.length) {
                                    item.options.imgList[indexs] = proItem.map(
                                        ({ couponAcquiredNumber, id, couponId, couponInfo }) => {
                                            const item = {
                                                ...couponInfo
                                            };
                                            // receiveStatus:1表示已领完 2表示领取已达上限
                                            item.receiveStatus =
                                                item.couponTotal - couponAcquiredNumber == 0
                                                    ? 1
                                                    : item?.acquireLimit
                                                    ? '2'
                                                    : '';
                                            item.content = couponContent(item);
                                            item.id = id;
                                            item.couponId = couponId;

                                            return item;
                                        }
                                    )[0];
                                } else {
                                    item.options.imgList[indexs] = null;
                                }
                            });
                        }
                        if (name == 'groupbuy') {
                            if (item.options.addType == 1) {
                                item.options.imgList.forEach((id, indexs) => {
                                    let proItem = imgLists[name].filter(val => val.id == id);
                                    if (proItem.length) {
                                        item.options.imgList[indexs] = proItem[0];
                                    } else {
                                        item.options.imgList[indexs] = null;
                                    }
                                });
                            } else {
                                let typeList = ['have_group_goods_num', 'activity_end_time', 'activity_start_time'];
                                const groupAuto = await request('groupList', {
                                    autogather: 1,
                                    direction: 'desc',
                                    activityType: item.options.groupType,
                                    reorder: typeList[item.options.rule - 1]
                                });
                                item.options.imgList = isNotEmpty(groupAuto?.data) ? groupAuto?.data : [];
                            }
                        }
                        return item;
                    })
                );
                // 过滤删除商品，当选择商品全部删除后，删除组件不再显示
                options.data.components = param
                    .map(item => {
                        item.options.imgList = item?.options?.imgList?.filter(fItem => fItem);
                        return item;
                    })
                    .filter(item => !item.options.imgList || item.options?.imgList.length > 0);
                isDecorate.value = true;
            } else {
                Object.assign(options, { data: {}, shareImg: '', shareTitle: '' });
                isDecorate.value = false;
            }
            loadData.value = true;
            skeletonLoading.value = false;
        })
        .catch(error => {
            if (skeletonLoading.value) state.networkErrorShow = true;
            skeletonLoading.value = false;
            if (isObject(error)) {
                uni.showToast({
                    title: error.data.msg,
                    icon: 'none',
                    duration: 2000
                });
            }
        });
};
onHide(() => {
    traceStay();
});
// onShareAppMessage(res => {
//     return {
//         title: options.shareTitle ? options.shareTitle : '',
//         path: '/pages/tabbar/home?shopId=' + storage.get('ZW_SHOP_ID'),
//         imageUrl: options.shareImg ? options.shareImg : ''
//     };
// });
const change = type => {
    goodsData.show = type.show;
};
/**
 * 关闭规格弹框
 * @param {*} param
 */
const close = param => {
    popup.value.close();
    if (type.value == 'left') {
        lefthotGoods.value[hotIndex.value].cartNum += param.quantity;
    } else {
        righthotGoods.value[hotIndex.value].cartNum += param.quantity;
    }
    goodsData.show = false;
};
const cancel = () => {
    popup.value.close();
    goodsData.show = false;
};
onPageScroll(e => {
    scrollTop.value = e.scrollTop;
});
const toConfirm = val => {
    popup.value.close();
    let { quantity, skuId, goodsId } = val;
    router.push({
        path: '/pages-cart/confirm/index',
        query: {
            skuList: JSON.stringify([{ goodsId, quantity, skuId }])
        }
    });
};
</script>
<style lang="scss" src="./home.scss" scoped></style>
